<template>
  <div class="get-json">
    <div class="table">
      <div>
        <div v-for="(a, b) in columns" :key="b">
          <el-input v-model="columns[b]" placeholder="请输入参数" style="width: 100%;" />
        </div>
      </div>
      <div v-for="(x, y) in list" :key="y">
        <div v-for="(a, b) in columns" :key="b">
          <el-input v-model="list[y][a]" placeholder="请输入数据" style="width: 100%;" />
        </div>
      </div>
    </div>
    <div v-if="list.length > 1">
      <div v-for="(x, y) in list" :key="y">
        {{ x }}
      </div>
    </div>
    <div style="margin: 10px 0;"><el-input v-model="path" placeholder="请输入数据" style="width: 500px;" /></div>
    <div>
      <el-button @click="addCol">增加行</el-button>
      <el-button @click="addRow">增加列</el-button>
      <el-button @click="addData">生成数据</el-button>
      <el-button @click="addFile">生成文件</el-button>
      <el-button @click="restart">重置</el-button>
    </div>
  </div>
</template>
<script setup>
import { onMounted, ref, getCurrentInstance } from 'vue';
const columns = ref([])
const list = ref([])
const { proxy } = getCurrentInstance()
const path = ref('')
onMounted(() => {
  let arr = list.value
  arr.push(newDate())
  path.value = __dirname.split('node')[0] + `src/renderer/src/json/`
})

function addData() {
  list.value = newList()
}

const addCol = () => {
  if (columns.value.length == 0) {
    proxy.$element.error('参数不能为空')
    return
  }
  let arr = list.value
  arr.push(newDate())
}

function restart() {
  list.value = []
  columns.value = []
}

function newDate() {
  let obj = {}
  columns.value.map(x => {
    obj[x] = ''
  })
  return obj
}

function newObj(old) {
  let obj = {}
  columns.value.map(a => {
    obj[a] = old[a]
  })
  return obj
}


function newList() {
  let arr = []
  list.value.map(a => {
    arr.push(newObj(a))
  })
  return arr
}


const addFile = () => {
  let content = JSON.stringify({
    list: list.value
  })
  const url = path.value + new Date().getTime() + '.json'
  proxy.$system.writeFile(url, content).then((res) => {
    // console.log(res)
  })
}

const addRow = () => {
  let arr = columns.value
  arr.push('')
  columns.value = arr
}



</script>
<style scoped lang="scss">
.table {
  >div:first-child {
    margin-bottom: 5px;
    padding-bottom: 5px;
    border-bottom: 1px solid #000;
  }

  >div {
    display: flex;

    >div {
      width: 100px;
      text-align: center;
      height: 45px;
      padding: 5px;
      margin: 2px;
      border: 1px solid #000;
    }
  }

  >div:last-child {
    border-top: 0;
  }
}
</style>
